package com.apkcore.core.util

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.util.Log
import androidx.annotation.ColorInt
import com.apkcore.core.R

object ForegroundNotifyUtil {
    private const val TAG = "ForegroundNotifyUtil"

    fun sendForegroundNotify(
        context: Service, clazz: Class<*>,
        smallIcon: Int,
        titleName: String = "前台服务",
        contentText: String = "服务运行中",
        @ColorInt argb: Int = Color.WHITE,
        chanId: String? = "",
    ) {
        val pendingIntent: PendingIntent = Intent(context, clazz).let { notificationIntent ->
            PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE)
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val chanIdStr = chanId ?: "${context::class.java.simpleName}-channel"
            val chan = NotificationChannel(
                chanIdStr, titleName, NotificationManager.IMPORTANCE_HIGH
            )
            chan.lightColor = Color.BLUE//通知灯，没啥用
            chan.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
            val service = context.getSystemService(Service.NOTIFICATION_SERVICE) as NotificationManager
            service.createNotificationChannel(chan)
            Log.d(TAG, "服务调用startForeground")

            val notification: Notification =
                Notification.Builder(context.applicationContext, chanId).setContentTitle(titleName)
                    .setContentText(contentText).setColor(argb)
                    .setSmallIcon(smallIcon).setContentIntent(pendingIntent).build()
            context.startForeground(1, notification)
        } else {
            Log.e(TAG, "${Build.VERSION.SDK_INT} < O(API 26) ")
        }
    }
}